package com.andy.mall.product.service.impl;

import com.andy.mall.product.entity.BrandEntity;
import com.andy.mall.product.entity.CategoryEntity;
import com.andy.mall.product.service.BrandService;
import com.andy.mall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andy.common.utils.PageUtils;
import com.andy.common.utils.Query;

import com.andy.mall.product.dao.CategoryBrandRelationDao;
import com.andy.mall.product.entity.CategoryBrandRelationEntity;
import com.andy.mall.product.service.CategoryBrandRelationService;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveCategoryBrandRelation(CategoryBrandRelationEntity categoryBrandRelation) {
        BrandEntity byId = brandService.getById(categoryBrandRelation.getBrandId());
        CategoryEntity catId = categoryService.getById(categoryBrandRelation.getCatelogId());
        categoryBrandRelation.setBrandName(byId.getName());
        categoryBrandRelation.setCatelogName(catId.getName());
        baseMapper.insert(categoryBrandRelation);
    }

    @Override
    public void updateByBrandId(Long brandId, String name) {
        CategoryBrandRelationEntity cbre=new CategoryBrandRelationEntity();
        cbre.setBrandId(brandId);
        cbre.setBrandName(name);
        baseMapper.update(cbre, new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id",brandId));
    }

    @Override
    public List<BrandEntity> getBrandsByCatId(Long catId) {
        List<CategoryBrandRelationEntity> list = baseMapper.selectList(new QueryWrapper<CategoryBrandRelationEntity>().eq("catelog_id", catId));
        List<Long> longs = list.stream().map((entity) -> {
            return entity.getBrandId();
        }).collect(Collectors.toList());
        List<BrandEntity> entities = brandService.listByIds(longs);
        return entities;
    }

}